from PyQt5.QtWidgets import (
    QWidget, QTableView, QVBoxLayout, QHBoxLayout,
    QLineEdit, QLabel, QHeaderView
)
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt5.QtGui import QIcon, QFont
import requests


class OrderTableModel(QAbstractTableModel):
    def __init__(self, orders=None):
        super().__init__()
        self.orders = orders or []
        self.headers = ["ID", "客户名称", "客户邮箱", "订单日期", "商品ID", "数量", "价格"]

    def rowCount(self, parent=None):
        return len(self.orders)

    def columnCount(self, parent=None):
        return len(self.headers)

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            order = self.orders[index.row()]
            return QVariant([
                order["id"],
                order["customer_name"],
                order["customer_email"],
                order["order_date"],
                order["product_id"],
                order["quantity"],
                f"¥{order['price']:.2f}"
            ][index.column()])
        return QVariant()

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.DisplayRole and orientation == Qt.Horizontal:
            return QVariant(self.headers[section])
        return QVariant()


class OrderManagementWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowIcon(QIcon('./images/购物.png'))
        self.all_orders = []
        self.init_ui()
        self.load_orders()

    def init_ui(self):
        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)

        # 标题
        title = QLabel("订单管理")
        title.setFont(QFont("Microsoft YaHei", 20, QFont.Bold))
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("""
            QLabel {
                color: white;
                padding: 10px;
                background-color: #ff5f00;
                border-radius: 8px;
            }
        """)
        layout.addWidget(title)

        # 创建搜索布局
        search_layout = QHBoxLayout()
        search_layout.addWidget(QLabel("搜索:"))
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入客户名称或邮箱进行搜索...")
        self.search_input.textChanged.connect(self.filter_orders)
        self.search_input.setStyleSheet("""
            QLineEdit {
                padding: 10px;
                border: 2px solid #ff5f00;
                border-radius: 10px;
                font-size: 20px;
                background-color: white;
            }
            QLineEdit:focus {
                border-color: #e65b00;
            }
        """)
        search_layout.addWidget(self.search_input)
        layout.addLayout(search_layout)

        # 添加状态标签
        self.status_label = QLabel("准备就绪")
        self.status_label.setStyleSheet("""
            QLabel {
                color: #666;
                font-size: 12px;
                padding: 5px;
            }
        """)
        layout.addWidget(self.status_label)

        # 创建订单表格
        self.order_table = QTableView()
        self.order_table.setSelectionMode(QTableView.SingleSelection)
        self.order_table.setSelectionBehavior(QTableView.SelectRows)
        self.order_table.setAlternatingRowColors(True)
        self.order_table.setStyleSheet("""
            QTableView {
                gridline-color: #ddd;
                background-color: white;
                alternate-background-color: #f9f9f9;
                selection-background-color: #ffe5cc;
                border: 2px solid #ddd;
                border-radius: 10px;
            }
            QTableView::item {
                padding: 8px;
                border-bottom: 1px solid #ddd;
            }
            QTableView::item:selected {
                background-color: #ff5f00;
                color: white;
            }
            QHeaderView::section {
                background-color: #f9f9f9;
                padding: 10px;
                border: none;
                border-bottom: 2px solid #ddd;
                font-weight: bold;
                color: #333;
            }
        """)
        layout.addWidget(self.order_table)

        self.setLayout(layout)
        self.model = OrderTableModel()
        self.order_table.setModel(self.model)
        self.order_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.order_table.horizontalHeader().setStretchLastSection(True)

    def load_orders(self):
        try:
            response = requests.get("http://127.0.0.1:8000/api/orders/")
            if response.status_code == 200:
                self.all_orders = response.json()
                self.model = OrderTableModel(self.all_orders)
                self.order_table.setModel(self.model)
                self.status_label.setText(f"加载 {len(self.all_orders)} 条订单")
            else:
                self.status_label.setText("加载订单失败")
                print(f"加载订单失败: {response.status_code} - {response.text}")
        except Exception as e:
            self.status_label.setText("加载订单失败")
            print(f"加载订单时发生错误: {e}")

    def filter_orders(self, text):
        if not text:
            self.model = OrderTableModel(self.all_orders)
        else:
            filtered = [order for order in self.all_orders if
                        text.lower() in order["customer_name"].lower() or text.lower() in order[
                            "customer_email"].lower()]
            self.model = OrderTableModel(filtered)
        self.order_table.setModel(self.model)